<template>
  <div>
    <van-nav-bar
      title="注册"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />

    <van-form>
      <van-field
        v-model="nickname"
        required
        label="用户名"
        placeholder="用户名"
      />
      <van-field
        v-model="password"
        type="password"
        required
        label="密码"
        placeholder="密码"
      />
      <van-field
        v-model="passwordRep"
        type="password"
        required
        label="密码"
        placeholder="密码"
      />
      <van-field v-model="realname" required label="姓名" placeholder="姓名" />
      <van-field label="性别" >
        <template #input>
        <van-radio-group v-model="userSex" direction="horizontal">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
        </van-radio-group>
        </template>
      </van-field>
      <van-field
        v-model="tel"
        required
        label="手机号"
        placeholder="手机号"
        :rules="[
          { required: true },
          { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式错误' },
        ]"
      />
      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          @click="onSubmit"
          >注册</van-button
        >
      </div>
    </van-form>
  </div>
</template>
<script>
import { Toast } from "vant";

export default {
  data() {
    return {
      nickname: "",
      password: "",
      passwordRep: "",
      realname: "",
      tel: "",
      userSex: "",
    };
  },
  methods: {
    onClickLeft() {
      this.$router.go(-1);
    },
    onSubmit() {
      if (
        this.nickname == "" ||
        this.password == "" ||
        this.passwordRep == "" ||
        this.realname == "" ||
        this.tel == "" ||
        this.userSex == ""
      ) {
        Toast("注册失败，信息不全");
      } else if (this.password != this.passwordRep) {
        Toast("密码输入两次不一致");
      } else {
        //alert(this.nickname)
        this.$axios
          .post("/user/add", {
            userNickname: this.nickname,
            userPassword: this.password,
            userRealname: this.realname,
            userTel: this.tel,
            userSex: this.userSex,
          })
          .then((res) => {
            if (res.data.code == 200) {
              Toast.success("注册成功");
              this.$notify({
                type: "success",
                message: "注册成功，3s后返回登录",
                duration: 3000,
              });
              setTimeout(() => {
                sessionStorage.clear("regis");
                this.$router.go(-1);
              }, 3000);
              this.$router.push({ path: "/user/login", query: this });
            }
          })
          .Error((error) => {
            console.error();
          });
      }
    },
  },
};
</script>